#!/usr/bin/env node
import fs from "fs";
import path from "path";
import prompts from "prompts";
import chalk from "chalk";
import prettier from "prettier";
import imagemin from "imagemin";
import imageminJpegtran from "imagemin-jpegtran";
import imageminPngquant from "imagemin-pngquant";

/**
 * 清理 README.md 文件中的本地引用链接
 */
function cleanReadMe() {
  const filePath = "README.md";

  // 检查文件是否存在
  if (!fs.existsSync(filePath)) {
    console.log(chalk.red(`${filePath} does not exist.`));
    return;
  }

  try {
    // 读取文件内容
    const readmeText = fs.readFileSync(filePath, "utf8");

    // 去掉对本地代码文件的引用链接
    const updatedText = readmeText.replace(
      /\[([^\]]+)\]\(file:\/\/[^\)]+\)/g,
      "`$1`",
    );

    // 写回更新后的内容
    fs.writeFileSync(filePath, updatedText, "utf8");
    console.log(chalk.green(`Successfully cleaned ${filePath}`));
  } catch (error) {
    console.log(chalk.red(`Failed to clean ${filePath}: ${error.message}`));
  }
}

/**
 * 删除 node_modules 文件夹
 */
function deleteNodeModules() {
  const dirPath = "node_modules";

  // 检查文件夹是否存在
  if (!fs.existsSync(dirPath)) {
    console.log(chalk.yellow(`${dirPath} does not exist. Nothing to delete.`));
    return;
  }

  try {
    // 递归删除文件夹
    fs.rmSync(dirPath, { recursive: true, force: true });
    console.log(chalk.green(`Successfully deleted ${dirPath}`));
  } catch (error) {
    console.log(chalk.red(`Failed to delete ${dirPath}: ${error.message}`));
  }
}

/**
 * 清理 .DS_Store 文件
 */
function cleanDSStore() {
  const dirPath = "."; // 当前目录

  try {
    // 递归查找 .DS_Store 文件
    const files = getAllFiles(dirPath);
    const dsStoreFiles = files.filter((file) => file.endsWith(".DS_Store"));

    if (dsStoreFiles.length === 0) {
      console.log(chalk.yellow("No .DS_Store files found."));
      return;
    }

    // 删除找到的 .DS_Store 文件
    dsStoreFiles.forEach((file) => {
      fs.unlinkSync(file);
      console.log(chalk.green(`Deleted: ${file}`));
    });

    console.log(
      chalk.green(
        `Successfully cleaned ${dsStoreFiles.length} .DS_Store files.`,
      ),
    );
  } catch (error) {
    console.log(chalk.red(`Failed to clean .DS_Store files: ${error.message}`));
  }
}

/**
 * 清理缓存文件夹
 */
function cleanCache() {
  const cachePatterns = [".cache", ".tmp"]; // 定义缓存文件夹名称
  const dirPath = "."; // 当前目录

  try {
    // 查找匹配的缓存文件夹
    const files = fs.readdirSync(dirPath);
    const cacheDirs = files.filter((file) => cachePatterns.includes(file));

    if (cacheDirs.length === 0) {
      console.log(chalk.yellow("No cache folders found."));
      return;
    }

    // 删除匹配的缓存文件夹
    cacheDirs.forEach((cacheDir) => {
      const fullPath = `${dirPath}/${cacheDir}`;
      fs.rmSync(fullPath, { recursive: true, force: true });
      console.log(chalk.green(`Deleted: ${fullPath}`));
    });

    console.log(
      chalk.green(`Successfully cleaned ${cacheDirs.length} cache folders.`),
    );
  } catch (error) {
    console.log(chalk.red(`Failed to clean cache folders: ${error.message}`));
  }
}

/**
 * 自动格式化代码
 */
async function formatCode() {
  const supportedExtensions = [".js", ".ts", ".json"]; // 支持的文件类型
  const dirPath = "."; // 当前目录

  try {
    // 获取所有支持的代码文件
    const files = getAllFiles(dirPath);
    const codeFiles = files.filter((file) =>
      supportedExtensions.some((ext) => file.endsWith(ext)),
    );

    if (codeFiles.length === 0) {
      console.log(chalk.yellow("No code files found to format."));
      return;
    }

    // 格式化每个文件
    for (const file of codeFiles) {
      const content = fs.readFileSync(file, "utf8");
      const formatted = await prettier.format(content, { filepath: file });
      fs.writeFileSync(file, formatted, "utf8");
      console.log(chalk.green(`Formatted: ${file}`));
    }

    console.log(
      chalk.green(`Successfully formatted ${codeFiles.length} code files.`),
    );
  } catch (error) {
    console.log(chalk.red(`Failed to format code: ${error.message}`));
  }
}

/**
 * 压缩图片资源
 */
async function compressImages() {
  const imageExtensions = [".jpg", ".jpeg", ".png"]; // 支持的图片类型
  const dirPath = "."; // 当前目录

  try {
    // 获取所有图片文件
    const files = getAllFiles(dirPath);
    const imageFiles = files.filter((file) =>
      imageExtensions.some((ext) => file.endsWith(ext)),
    );

    if (imageFiles.length === 0) {
      console.log(chalk.yellow("No image files found to compress."));
      return;
    }

    // 压缩图片
    const compressedFiles = await imagemin(imageFiles, {
      plugins: [
        imageminJpegtran(),
        imageminPngquant({
          quality: [0.6, 0.8], // 设置压缩质量
        }),
      ],
    });

    // 输出压缩结果
    compressedFiles.forEach((file) => {
      console.log(chalk.green(`Compressed: ${file.sourcePath}`));
    });

    console.log(
      chalk.green(
        `Successfully compressed ${compressedFiles.length} image files.`,
      ),
    );
  } catch (error) {
    console.log(chalk.red(`Failed to compress images: ${error.message}`));
  }
}

/**
 * 获取指定目录下的所有文件（递归）
 * @param {string} dir - 目录路径
 * @returns {string[]} - 文件路径列表
 */
function getAllFiles(dir) {
  let results = [];
  const list = fs.readdirSync(dir);

  list.forEach((file) => {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    // 跳过 node_modules 文件夹
    if (filePath.includes("node_modules")) {
      return;
    }

    if (stat && stat.isDirectory()) {
      // 递归处理子目录
      results = results.concat(getAllFiles(filePath));
    } else {
      results.push(filePath);
    }
  });

  return results;
}

/**
 * 主函数：提供交互式选择
 */
async function main() {
  // 定义可操作选项
  const choices = [
    {
      title: "Clean README.md",
      description: "Remove local file references in README.md",
      value: "cleanReadMe",
    },
    {
      title: "Delete node_modules",
      description: "Remove the node_modules folder",
      value: "deleteNodeModules",
    },
    {
      title: "Clean .DS_Store Files",
      description: "Remove all .DS_Store files",
      value: "cleanDSStore",
    },
    {
      title: "Clean Cache Folders",
      description: "Remove common cache folders (.cache, .tmp)",
      value: "cleanCache",
    },
    {
      title: "Format Code",
      description: "Auto-format code files using Prettier",
      value: "formatCode",
    },
    {
      title: "Compress Images",
      description: "Compress image files using imagemin",
      value: "compressImages",
    },
  ];

  // 提示用户选择操作
  const response = await prompts({
    type: "select",
    name: "action",
    message: "Select an action:",
    choices: choices,
    hint: "- Use arrow keys to select. Press Enter to confirm.",
  });

  // 根据用户选择执行对应操作
  switch (response.action) {
    case "cleanReadMe":
      cleanReadMe();
      break;
    case "deleteNodeModules":
      deleteNodeModules();
      break;
    case "cleanDSStore":
      cleanDSStore();
      break;
    case "cleanCache":
      cleanCache();
      break;
    case "formatCode":
      await formatCode();
      break;
    case "compressImages":
      await compressImages();
      break;
    default:
      console.log(chalk.yellow("No action selected. Exiting..."));
  }
}

// 执行主函数
main().catch((error) => {
  console.log(chalk.red(`An error occurred: ${error.message}`));
});
